package sf.database.jdbc.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;

public class DateTIMESTAMPType implements TypeHandler<Date> {
    public Date get(ResultSet rs, String colName) throws SQLException {
        return rs.getTimestamp(colName);
    }

    public Date get(ResultSet rs, int index) throws SQLException {
        return rs.getTimestamp(index);
    }

    public Date get(CallableStatement rs, int index) throws SQLException {
        return rs.getTimestamp(index);
    }

    @Override
    public Date get(CallableStatement cs, String parameterName) throws SQLException {
        return cs.getTimestamp(parameterName);
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        rs.updateTimestamp(columnLabel, changeTimestampType(value));
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        rs.updateTimestamp(columnIndex, changeTimestampType(value));
    }

    public Object set(PreparedStatement stat, Object value, int i) throws SQLException {
        if (null == value) {
            stat.setNull(i, getSqlType());
        } else {
            stat.setTimestamp(i, changeTimestampType(value));
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object value, String parameterName) throws SQLException {
        if (null == value) {
            cs.setNull(parameterName, getSqlType());
        } else {
            cs.setTimestamp(parameterName, changeTimestampType(value));
        }
        return null;
    }

    @Override
    public int getSqlType() {
        return Types.TIMESTAMP;
    }

    @Override
    public Class<Date> getDefaultJavaType() {
        return Date.class;
    }

    protected static Timestamp changeTimestampType(Object value) {
        if (Timestamp.class.isAssignableFrom(value.getClass())) {
            return (Timestamp) value;
        } else if (Date.class.isAssignableFrom(value.getClass())) {
            return new Timestamp(((Date) value).getTime());
        } else if (Number.class.isAssignableFrom(value.getClass())) {
            return new Timestamp(((Number) value).longValue());
        }
        return null;
    }
}
